<template>
  <div class="center">
    <el-button class="outLogin" @click="isShowDialog = true">{{
      $t("user.editAvatar")
    }}</el-button>
    <el-dialog
      :title="$t('user.editAvatar')"
      :visible.sync="isShowDialog"
      width="1000px"
      @close="closeDialog"
    >
      <input
        type="file"
        style="display: none"
        id="input-file"
        accept="image/png, image/jpeg, image/jpg, image/bmp"
        @change="uploadImg($event)"
      />
      <el-row>
        <div v-if="isShowFileButton" class="center" style="height: 400px">
          <el-popover
            trigger="hover"
            :content="$t('user.selectAvatarTip', [imageMaxSize])"
          >
            <div class="choose-file-btn" @click="changeFile" slot="reference">
              {{ $t("user.selectAvatar") }}
            </div>
          </el-popover>
        </div>
        <div v-else class="center">
          <vueCropper
            style="width: 550px; height: 400px"
            ref="cropper"
            :img="options.img"
            :auto-crop="options.autoCrop"
            :fixed-box="options.fixedBox"
            :can-move-box="options.canMoveBox"
            :auto-crop-width="options.autoCropWidth"
            :auto-crop-height="options.autoCropHeight"
            :center-box="options.centerBox"
            @realTime="realTime"
          >
          </vueCropper>
        </div>
        <!-- <el-col :span="8" style="height: 400px;">
          <h2 style="text-align: center; line-height: 50px">头像预览</h2>
          <div class="show-preview">
            <div style="height: 200px; width: 200px" class="preview">
              <img :src="previews.url" :style="previews.img" alt="" />
            </div>
          </div>
          <div v-show="!isShowFileButton" class="preview-footer">
            <el-button @click="changeFile">更 换 图 片</el-button>
          </div>
        </el-col> -->
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">{{
          $t("common.cancel")
        }}</el-button>

        <router-link
          :to="{
            path: `/member/${this.username}/setting`,
          }"
          style="margin-left: 1em"
        >
          <el-button
            type="primary"
            @click="commitCut"
            v-loading.fullscreen.lock="fullscreenLoading"
            :disabled="Object.keys(previews).length === 0"
            >{{ $t("common.submit") }}</el-button
          >
        </router-link>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/util/auth";
export default {
  name: "CutPortrait",
  props: {
    // 上传地址
    UploadUrl: {
      type: String,
      require: true,
    },
    // 图片的大小限制，默认 10 MB
    imageMaxSize: {
      type: Number,
      default: 10,
    },
    Theid: {
      type: Object,
      require: true,
    },
    //
    username: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      file: "",
      isShowDialog: false, // 弹窗状态
      isShowFileButton: true, // 选择文件的按钮状态
      options: {
        // vue-cropper的参数
        img: "", //裁剪的图片blob地址
        autoCrop: true, //默认生成截图框
        fixedBox: true, //固定截图框大小
        canMoveBox: false, //截图框不能拖动
        autoCropWidth: 200, //截图框宽度
        autoCropHeight: 200, //截图框高度
        centerBox: true, //截图框被限制在图片里面
      },
      previews: {}, // 预览图对象
      fullscreenLoading: false, // 全屏加载遮罩状态
      imageUrl: "", // 上传后的图片地址
    };
  },
  methods: {
    // 关闭截图对话框弹窗
    closeDialog() {
      this.isShowDialog = false;
      this.previews = {};
      this.isShowFileButton = true;
    },
    // 点击选择图片或更换图片按钮，变更裁剪图片
    changeFile() {
      let inputFile = document.getElementById("input-file");
      inputFile.value = "";
      inputFile.click();
    },
    // 变更裁剪图片
    uploadImg(e) {
      this.file = e.target.files[0];
      // 判断文件格式是否符合要求规范
      if (this.file === undefined) {
        return false;
      }
      if (!/\.(jpg|jpeg|png|bmp|JPG|PNG)$/.test(e.target.value)) {
        this.$message.error(this.$t("user.errAvatar"));
        return false;
      }
      // 判断文件是否超出大小限制
      if (this.file.size / 1024 / 1024 > this.imageMaxSize) {
        this.$message.error(this.$t("user.selectAvatarTip", [imageMaxSize]));
        return false;
      }
      //fileReader 接口，用于异步读取文件数据
      let reader = new FileReader();
      reader.readAsDataURL(this.file); //重要 以dataURL形式读取文件
      reader.onload = (e) => {
        // this.options.img = window.URL.createObjectURL(new Blob([e.target.result])) 转化为blob格式
        this.options.img = e.target.result;
        // 转化为base64
        // reader.readAsDataURL(file)
        // 转化为blob
      };
      this.isShowFileButton = false;
    },
    // 同步实时预览的数据
    realTime(data) {
      this.previews = data;
    },
    //确认截图,上传到后台
    commitCut() {
      this.fullscreenLoading = true;
      let formData = new FormData();
      this.$refs.cropper.getCropBlob((res) => {
        //res是裁剪后图片的blob对象,遍历组件上传数据的对象 => 添加到formData对象中
        formData.append("file", res);
        this.$http({
          url: this.UploadUrl,
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data;charset=utf-8",
            Authorization: "Bearer " + getToken(),
          },
        }).then((res) => {
          this.$message.success(this.$t("user.editAvatarSuccess"));
          res = res.data;
          if (res.code == 200) {
            this.imageUrl = res.data;
            this.closeDialog();
            this.fullscreenLoading = false;
            this.SetUrl();
          } else {
            this.fullscreenLoading = false;
          }
        });
      });
    },
    // 将裁剪后的图片传出的父组件
    SetUrl() {
      this.$emit("getUrl", this.imageUrl);
    },
  },
};
</script>

<style scoped>
.cropper-box {
  width: 100%;
  height: 100%;
}

.choose-file-btn {
  width: 160px;
  height: 80px;
  font-size: 22px;
  font-weight: 600;
  line-height: 80px;
  text-align: center;
  color: #333;
  border: #aaa 1px solid;
  cursor: pointer;
  transition: 0.25s;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
}

.choose-file-btn:hover {
  color: #fff;
  background: #00d7c6;
  border: #00d7c6 1px solid;
  transform: scale(1.15);
}
</style>
 